const {verify} = require('../utils/jwt')
const {formatResponseData} = require("../utils/response");
const {parse} = require('node:url')
const {findGithub} = require('../services/githubServices');
const {findUser} = require('../services/userServices')


/**
 * 解析token中间件
 * @param req
 * @param res
 * @param next
 * @return {Promise<*>}
 */

const requestWhiteList = ["/api/user/login", '/api/github/clientId', '/api/github/getToken'];

async function auth(req, res, next) {
    const originalUrl = parse(req.originalUrl).pathname;
    if (requestWhiteList.includes(originalUrl) || !originalUrl.startsWith('/api')) {
        //    进入白名单的请求不验证token
        return next();
    }
    // 从请求头中获取 Authorization 字段的值
    const Authorization = req.header('Authorization');
    const token = Authorization ? req.header('Authorization').replace('Bearer ', '') : null

    if (!token) {
        // 未提供令牌，返回错误信息
        return res.send(formatResponseData(401, null, '您尚未登录，请先登录'));
    }

    let decoded;

    // 验证令牌并解码
    try {
        decoded = verify(token);
    } catch {
        return res.send(formatResponseData(401, null, '登录凭证过期，请先登录'));
    }

    const find = decoded.type === 'account' ? findUser : findGithub


    const user = await find({_id: decoded.id});
    if (!user || user.length === 0) {
        return res.send(formatResponseData(401, null, '登录凭证错误，请重试'));
    }
    req.user = user[0];
    next();

}

module.exports = {
    auth
}